//
//  recommendController.m
//  Focus
//
//  Created by dlios on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "recommendController.h"
#import "ThreeImageCell.h"
#import "addMoreController.h"
#import "OneImageCell.h"
#import "AFNetworking.h"
#import "recommendModel.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "NoImageCell.h"
#import "MJRefresh.h"
#import "webViewController.h"
@interface recommendController ()

@end

@implementation recommendController
-(void)dealloc{
    [_allUrl release];
    [_oneImage release];
    [_imageArray release];
    [_myDic release];
    [_table release];
    [_array release];
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.allUrl = [NSMutableArray array];
        self.oneImage = [NSMutableArray array];
        self.imageArray = [NSMutableArray array];
        self.array = [NSMutableArray array];
        self.myDic = [NSMutableDictionary dictionary];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(changeBackGroundColor:) name:@"color" object:nil];
        NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
        [notification addObserver:self selector:@selector(receiveNotification:) name:@"Night" object:nil];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    
#pragma mark -
#pragma mark - 导航栏标题设置
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    title.text = @"推荐";
    title.textColor = [UIColor whiteColor];
    title.font = [UIFont systemFontOfSize:18];
    title.textAlignment =  NSTextAlignmentCenter;
    title.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = title;
    [title release];
    
#pragma mark -
#pragma mark - 导航栏右边自定义button
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 40);
    [right setImage:[UIImage imageNamed:@"DailyHot_PreferencesButton_inDark.png"] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithCustomView:right]autorelease];
#pragma mark -
#pragma maek -创建tableview
    [self creatTableView];
#pragma mark -
#pragma mark - 注册cell
    [_table registerClass:[ThreeImageCell class] forCellReuseIdentifier:@"cellOne"];
    [_table registerClass:[OneImageCell class] forCellReuseIdentifier:@"cellTwo"];
    [_table registerClass:[NoImageCell class] forCellReuseIdentifier:@"cellThree"];
#pragma mark -
#pragma mark - 网络请求
    [self connect];
#pragma mark -
#pragma mark - 调用刷新加载
    [self setupRefresh];
}
#pragma mark -
#pragma mark - 导航栏右边自定义button点击事件
-(void)rightButtonAction:(UIBarButtonItem *)sender{
    addMoreController *addMore = [[addMoreController alloc]init];
    [self.navigationController pushViewController:addMore animated:YES];
    [addMore release];
    
}

#pragma mark -
#pragma mark - 创建tableView
-(void)creatTableView{
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    [self.view addSubview:_table];
}
#pragma mark -
#pragma mark - tableView必须实现的两个协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    recommendModel *recomend = [self.array objectAtIndex:indexPath.row];
    if ([recomend.imageCount count] == 3) {
        ThreeImageCell *cellOne = [tableView dequeueReusableCellWithIdentifier:@"cellOne"];
        cellOne.titleLabel.text = recomend.title;
        cellOne.autherName.text = recomend.authername;
        cellOne.date.text = recomend.date;
        
        [cellOne.leftImage sd_setImageWithURL:[NSURL URLWithString:recomend.leftImage]];
        [cellOne.minImage sd_setImageWithURL:[NSURL URLWithString:recomend.minImage]];
        [cellOne.rightImage sd_setImageWithURL:[NSURL URLWithString:recomend.rightImage]];
        if (self.count == 1) {
            cellOne.backgroundColor = [UIColor blackColor];
            cellOne.titleLabel.textColor = [UIColor grayColor];
            cellOne.autherName.textColor = [UIColor grayColor];
        }else{
            cellOne.backgroundColor = [UIColor whiteColor];
            cellOne.titleLabel.textColor = [UIColor blackColor];
            cellOne.autherName.textColor = [UIColor blackColor];
        }
        cellOne.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellOne;
    }
    else if([recomend.imageCount count] == 1) {
        OneImageCell *cellTwo = [tableView dequeueReusableCellWithIdentifier:@"cellTwo"];
        cellTwo.titleLabel.text = recomend.title;
        cellTwo.autherName.text = recomend.authername;
        [cellTwo.rightImage sd_setImageWithURL:[NSURL URLWithString:recomend.onceImage]];
        [cellTwo.icon sd_setImageWithURL:[NSURL URLWithString:recomend.specialinfo]];
        if (self.count == 1) {
            cellTwo.backgroundColor = [UIColor blackColor];
            cellTwo.titleLabel.textColor = [UIColor grayColor];
            cellTwo.autherName.textColor = [UIColor grayColor];
        }else{
            cellTwo.backgroundColor = [UIColor whiteColor];
            cellTwo.titleLabel.textColor = [UIColor blackColor];
            cellTwo.autherName.textColor = [UIColor blackColor];
        }
        cellTwo.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellTwo;
    }
    else{
        
        NoImageCell *cellThree = [tableView dequeueReusableCellWithIdentifier:@"cellThree"];
        cellThree.titleLabel.text = recomend.title;
        cellThree.autherName.text = recomend.authername;
        cellThree.icon.text = recomend.date;
        if (self.count == 1) {
            cellThree.backgroundColor = [UIColor blackColor];
            cellThree.titleLabel.textColor = [UIColor grayColor];
            cellThree.autherName.textColor = [UIColor grayColor];
        }else{
            cellThree.backgroundColor = [UIColor whiteColor];
            cellThree.titleLabel.textColor = [UIColor blackColor];
            cellThree.autherName.textColor = [UIColor blackColor];
        }
        cellThree.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellThree;
        
    }
    
    
    //    ThreeImageCell *cellOne = [tableView dequeueReusableCellWithIdentifier:@"cellOne"];
    //    return cellOne;
    return nil;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    recommendModel *recomend = [self.array objectAtIndex:indexPath.row];
    if ([recomend.imageCount count]==3)
    {
        return 180;
    }else if([recomend.imageCount count] == 1)
    {
        return 110;
    }else{
        return 100;
    }
    return 0;
}
#pragma mark -
#pragma mark - 点击cell进入下一页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    webViewController *web = [[webViewController alloc]init];
    web.recommend = [self.array objectAtIndex:indexPath.row];
    
    [self presentViewController:web animated:YES completion:^{
        
    }];
}
#pragma mark -
#pragma mark - 网络请求
-(void)connect{
    //风火轮
    MBProgressHUD *hub = [[MBProgressHUD alloc]initWithView:self.view];
    hub.labelText = @"加载";
    [hub setMode:MBProgressHUDModeIndeterminate];
    [hub show:YES];
    [self.view addSubview:hub];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"rootBlocks.plist"];
    NSMutableDictionary *myDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    NSMutableArray *array = [myDic objectForKey:@"blocksData"];
    NSString *url = [array[arc4random() % array.count]objectForKey:@"api_url"];
    [self.allUrl addObject:url];
    if (self.i == 0) {
        AFHTTPRequestOperationManager *mannegr = [AFHTTPRequestOperationManager manager];
        [mannegr.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
        [mannegr GET:@"http://iphone.myzaker.com/zaker/news.php?app_id=2&act=list"
          parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
              //        NSLog(@"%@",responseObject);
              self.myDic = responseObject;
              NSDictionary *dataDic = [self.myDic objectForKey:@"data"];
              NSArray *articlesArray = [dataDic objectForKey:@"articles"];
              
              for (NSDictionary *dic in articlesArray) {
                  
                  recommendModel *recomendModel = [[recommendModel alloc]initWithDic:dic];
                  [self.array addObject:recomendModel];
                  NSLog(@"%@",recomendModel.title);
                  NSLog(@"%@",recomendModel.specialinfo);
                  [recomendModel release];
                  
              }
              [hub removeFromSuperview];
              [_table reloadData];
              
              
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"%@",error);
          }];
#pragma mark -
#pragma mark - 请求第二次
        [mannegr GET:@"http://iphone.myzaker.com/zaker/news.php?app_id=4&act=list"
          parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
              //        NSLog(@"%@",responseObject);
              self.myDic = responseObject;
              NSDictionary *dataDic = [self.myDic objectForKey:@"data"];
              NSArray *articlesArray = [dataDic objectForKey:@"articles"];
              
              for (NSDictionary *dic in articlesArray) {
                  recommendModel *recomendModel = [[recommendModel alloc]initWithDic:dic];
                  [self.array addObject:recomendModel];
                  NSLog(@"%@",recomendModel.title);
                  NSLog(@"%@",recomendModel.specialinfo);
                  [recomendModel release];
              }
              [hub removeFromSuperview];
              [_table reloadData];
              
              
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"%@",error);
          }];
        //#pragma mark -
        //#pragma mark - 请求第四次
    
}

}


#pragma mark -
#pragma mark - 上拉刷新
-(void)setupRefresh
{
    
    //下拉刷新
    [self.table addHeaderWithTarget:self action:@selector(headerRefreshAction)];
    [self.table headerBeginRefreshing];
    //上拉加载更多
    [self.table addFooterWithTarget:self action:@selector(footerRefreshAction)];
    [self.table footerBeginRefreshing];
    
    //设置文字
    self.table.headerPullToRefreshText = @"下拉以刷新";
    self.table.headerReleaseToRefreshText = @"即将为你推荐10篇文章";
    self.table.headerRefreshingText = @"推荐中请稍后";
    self.table.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.table.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.table.footerRefreshingText = @"加载中";
    
    
}
#pragma mark -
#pragma mark - 开始进入刷新状态
-(void)headerRefreshAction{
    //    [self.table addHeaderWithCallback:^{
    //
    //        [self.array removeAllObjects];
    //        [self connect];
    //    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.table reloadData];
        
        [_table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table headerEndRefreshing];
    });
    
}
#pragma mark -
#pragma mark - 加载
-(void)footerRefreshAction{
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manger GET:[self.allUrl objectAtIndex:arc4random() % [self.allUrl count]] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        self.myDic = responseObject;
        NSDictionary *dataDic = [self.myDic objectForKey:@"data"];
        NSArray *articlesArray = [dataDic objectForKey:@"articles"];
        
        for (NSDictionary *dic in articlesArray) {
            
            recommendModel *recomendModel = [[recommendModel alloc]initWithDic:dic];
            [self.array addObject:recomendModel];
            NSLog(@"%@",recomendModel.title);
            NSLog(@"%@",recomendModel.specialinfo);
            [recomendModel release];
            
        }
        [_table reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table footerEndRefreshing];
        
    });
    
}
#pragma mark -
#pragma mark - 试图将要出现
-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = NO;
    
}
#pragma 消息中心的夜间模式
- (void)receiveNotification:(NSNotification *)notification
{
    //    self.receive = [notification.object integerValue];
    self.count = [night nightState].openStatu;
    if ([night nightState].openStatu == 1) {
        
        self.view.backgroundColor = [UIColor blackColor];
    }else{
        
        self.view.backgroundColor = [UIColor whiteColor];
    }
    [_table reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
